package xyz.chaobei.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import xyz.chaobei.entity.OrgUserRoleEntity;
import xyz.chaobei.entity.ro.OrgUserRoleRO;
import xyz.chaobei.service.OrgUserRoleService;
import xyz.chaobei.util.JsonUtil;

import javax.validation.Valid;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("api/orgUserRole")
public class OrgUserRoleController {

    @Autowired
    private OrgUserRoleService orgUserRoleService;

    @GetMapping("/{id}")
    public JSONObject get(@PathVariable("id") Integer id) {

        List<OrgUserRoleEntity> list = orgUserRoleService.findByUserId(id);
        List<Integer> result = list.stream().map(item -> item.getRoleId()).collect(Collectors.toList());

        return JsonUtil.getSuccess(result);
    }

    /**
     * 批量增加
     *
     * @param entity
     * @return
     */
    @PostMapping("/")
    public JSONObject save(@RequestBody @Valid OrgUserRoleRO entity) {

        UpdateWrapper wrapper = new UpdateWrapper();
        wrapper.eq("user_id_", entity.getUserId());

        boolean isDel = orgUserRoleService.remove(wrapper);

        List<OrgUserRoleEntity> roleEntityList = new LinkedList<>();

        entity.getRolesId().forEach(role -> {
            OrgUserRoleEntity item = new OrgUserRoleEntity();
            item.setUserId(entity.getUserId());
            item.setRoleId(role);

            roleEntityList.add(item);
        });
        boolean isSave = orgUserRoleService.saveBatch(roleEntityList);

        return JsonUtil.getResult(isSave);
    }

}
